<template>
  <div id="exercise-form" class="pore" v-loading="showLoading">
    <cus-Breadcrumb level1="习题管理" level2="习题分类" class="mb20"></cus-Breadcrumb>
    <el-select
      allow-create
      size="small"
      default-first-option
      v-model="ChildDictionaryList.content"
      placeholder="请选择子字典分类"
    >
      <el-option
        v-if="tkxtSearch"
        v-for="item in ChildDictionaryList"
        :key="item.id"
        :label="item.content"
        :value="item.alias"
        @click.native="searchExerciseByChildCategoryAlias(item)"
      ></el-option>
    </el-select>
    <div class="tipStyle2">
      <i class="el-icon-view"></i>
      默认查询全部习题，点击左侧下拉菜单根据分类查询习题
    </div>
    <el-table style="width: 100%" class="mt20" :data="tableData">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column label="题目" prop="content" width="600"></el-table-column>
      <el-table-column label="正确选项" width="100" prop="rightOption"></el-table-column>
      <el-table-column label="正确选项内容" width="500" prop="rightOptionContent"></el-table-column>
      <el-table-column label="分类" width="160" prop="kind" sortable>
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.kind === 0? '单选题': '判断题'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="快捷操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="showEditChild(scope)" v-if="tkxtEdit">编辑</el-button>
          <el-button size="mini" type="danger" @click.stop="removeExercise(scope)" v-if="tkxtDelete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="编辑习题" :visible.sync="editChild" class="dialog">
      <el-form status-icon ref="ruleForm2" label-width="140px" class="demo-ruleForm">
        <el-form-item label="试题内容" class="formItem">
          <el-input
            class="editInput excriseContent"
            type="textarea"
            autocomplete="off"
            v-model="editExerciseList.content"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题类型" class="formItem">
          <el-radio label="0" class="ml10" v-model="kinds" @change="pushkind">单选题</el-radio>
          <el-radio label="1" class="ml10" v-model="kinds" @change="pushkind" :disabled="true">判断题</el-radio>
        </el-form-item>
        <el-form-item label="试题类别" class="formItem">
          <el-select
            allow-create
            size="small"
            default-first-option
            v-model="item.id"
            placeholder="请选择子字典分类"
          >
            <el-option
              v-for="item in ChildCategoryList"
              :key="item.id"
              :label="item.content"
              :value="item.id"
              @click.native="changeEditExeciseCateId(item)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="A选项" class="limit-min-width" v-if="option.A">
          <el-input
            v-if="option.A"
            :disabled="!changeFlag"
            class="input-con excriseOption"
            placeholder="A选项"
            v-model="option.A.content"
          ></el-input>
          <el-radio
            v-if="option.A"
            label="A"
            class="ml10"
            @change="pushRigthOption"
            v-model="rightOption"
          >A为正确选项</el-radio>
        </el-form-item>
        <el-form-item label="B选项" class="limit-min-width" v-if="option.B">
          <el-input
            v-if="option.B"
            :disabled="!changeFlag"
            class="input-con excriseOption"
            placeholder="B选项"
            v-model="option.B.content"
          ></el-input>
          <el-radio
            v-if="option.B"
            label="B"
            class="ml10"
            @change="pushRigthOption"
            v-model="rightOption"
          >B为正确选项</el-radio>
        </el-form-item>
        <el-form-item label="C选项" class="limit-min-width" v-if="option.C && changeFlag">
          <el-input
            v-if="option.C"
            class="input-con excriseOption"
            placeholder="C选项"
            v-model="option.C.content"
          ></el-input>
          <el-radio
            v-if="option.C"
            label="C"
            class="ml10"
            @change="pushRigthOption"
            v-model="rightOption"
          >C为正确选项</el-radio>
        </el-form-item>
        <el-form-item label="D选项" class="limit-min-width" v-if="option.D && changeFlag">
          <el-input
            v-if="option.D"
            class="input-con excriseOption"
            placeholder="D选项"
            v-model="option.D.content"
          ></el-input>
          <el-radio
            v-if="option.D"
            label="D"
            class="ml10"
            @change="pushRigthOption"
            v-model="rightOption"
          >D为正确选项</el-radio>
        </el-form-item>
        <el-form-item label="E选项" class="limit-min-width" v-if="option.E && changeFlag">
          <el-input
            v-if="option.E"
            class="input-con excriseOption"
            placeholder="E选项"
            v-model="option.E.content"
          ></el-input>
          <el-radio
            v-if="option.E"
            label="E"
            class="ml10"
            @change="pushRigthOption"
            v-model="rightOption"
          >E为正确选项</el-radio>
        </el-form-item>
        <el-form-item label="F选项" class="limit-min-width" v-if="option.F && changeFlag">
          <el-input
            v-if="option.F"
            class="input-con excriseOption"
            placeholder="F选项"
            v-model="option.F.content"
          ></el-input>
          <el-radio
            v-if="option.F"
            label="F"
            class="ml10"
            @change="pushRigthOption"
            v-model="rightOption"
          >F为正确选项</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editExercise()">确 定</el-button>
        <el-button @click="closeEditExercise">取 消</el-button>
      </div>
    </el-dialog>
    <el-pagination
      class="pagenation"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="1"
      :page-sizes="[10]"
      :page-size="10"
      layout="total, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>
<script>
import $$ from '@/plugins/statusCode.config'
export default {
  data () {
    return {
      tkxtSearch: false,
      tkxtEdit: false,
      tkxtDelete: false,
      FatherDictionaryList: [],
      ChildDictionaryList: [],
      tableData: [],
      showLoading: false,
      editChild: false,
      editExerciseList: [],
      ChildCategoryList: [],
      parentCatId: '',
      option: {
        A: {
          letter: 'A',
          content: ''
        },
        B: {
          letter: 'B',
          content: ''
        },
        C: {
          letter: 'C',
          content: ''
        },
        D: {
          letter: 'D',
          content: ''
        },
        E: {
          letter: 'E',
          content: ''
        },
        F: {
          letter: 'F',
          content: ''
        }
      },
      optionObj: {
        A: {
          letter: 'A',
          content: '',
          id: ''
        },
        B: {
          letter: 'B',
          content: '',
          id: ''
        },
        C: {
          letter: 'C',
          content: '',
          id: ''
        },
        D: {
          letter: 'D',
          content: '',
          id: ''
        },
        E: {
          letter: 'E',
          content: '',
          id: ''
        },
        F: {
          letter: 'F',
          content: '',
          id: ''
        }
      },
      optionArr: [],
      optionStr: '',
      item: {},
      keyName: 'question',
      acategoryId: '',
      acategoryAlias: '',
      scope1: '',
      pageNo: 1,
      PageSize: 10,
      total: 0,
      rightOption: '',
      kinds: '',
      changeFlag: true,
      listArr: {
        A: {
          letter: 'A',
          content: ''
        },
        B: {
          letter: 'B',
          content: ''
        },
        C: {
          letter: 'C',
          content: ''
        },
        D: {
          letter: 'D',
          content: ''
        },
        E: {
          letter: 'E',
          content: ''
        },
        F: {
          letter: 'F',
          content: ''
        }
      }
    }
  },
  created () {
    this.showLoading = true
    this.searchChildDictionaryByKeyName(this.keyName)
    const token = sessionStorage.getItem('accessToken')
    if (!token) {
      this.$message.warning('请先登录')
      this.$router.push({ name: 'login' })
    }
    this.managerNickName = sessionStorage.getItem('managerNickName')
  },
  mounted () {
    this.role()
  },
  methods: {
    role () {
      let arr = JSON.parse(sessionStorage.getItem('buttonRole'))
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 'tkxt-search') {
          this.tkxtSearch = true
        }
        if (arr[i] === 'tkxt-edit') {
          this.tkxtEdit = true
        }
        if (arr[i] === 'tkxt-delete') {
          this.tkxtDelete = true
        }
      }
    },
    changeFlag1 () {
      // 选择题或者是判断题Flag
      this.changeFlag = true
      this.option.A.content = JSON.parse(this.listArr).A.content
      this.option.B.content = JSON.parse(this.listArr).B.content
    },
    changeFlag2 () {
      this.changeFlag = false
      this.option.A.content = '正确'
      this.option.B.content = '错误'
    },
    pushkind (scope) {
      this.kinds = scope
    },
    pushRigthOption (right) {
      this.editExerciseList.rightOption = right
      this.editExerciseList.rightOptionContent = this.option[right].content
    },
    closeEditExercise () {
      this.editChild = false
      this.editExerciseList.id = ''
      this.editExerciseList.content = ''
      this.editExerciseList.categoryId = ''
      this.editExerciseList.categoryAlias = ''
      this.editExerciseList.rightOption = ''
      this.editExerciseList.rightOptionContent = ''
    },
    handleSizeChange (val) {
      this.PageSize = val
      if (this.item.alias) {
        this.searchExerciseByChildCategoryAlias(this.item)
      } else {
        this.searchAllExcrise()
      }
    },
    handleCurrentChange (val) {
      this.pageNo = val
      if (this.item) {
        this.searchExerciseByChildCategoryAlias(this.item)
      } else {
        this.searchAllExcrise()
      }
    },
    async searchChildDictionaryByKeyName (keyName) {
      const that = this
      const param = new URLSearchParams()
      param.append('keyName', keyName)
      await this.$http8081
        .post(`/dictionary-search/flipListByKeyName`, param)
        .then(function (res) {
          that.showLoading = false
          if (res.data.statusCode === $$.s20006) {
            that.ChildCategoryList = res.data.data
            that.ChildDictionaryList = res.data.data
            that.searchAllExcrise()
          }
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.searchChildDictionaryByKeyName(_that.keyName)
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  _that.$router.push({ name: 'login' })
                  _that.$message.success('登陆超时请重新登陆')
                }
              })
          }
        })
    },
    async searchAllExcrise () {
      this.showLoading = true
      const that = this
      const param = new URLSearchParams()
      // param.append('categoryId', that.item.id)
      // param.append('categoryAlias', '')
      param.append('pageNo', this.pageNo)
      param.append('PageSize', this.PageSize)
      await this.$http8081
        .post(`/question-search/flipListByCategoryAlias`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s20006) {
            that.total = res.data.data.total
            that.showLoading = false
            that.tableData = res.data.data.records
            that.$message.success(res.data.statusMsg)
          }
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.searchAllExcrise()
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  _that.$router.push({ name: 'login' })
                  _that.$message.success('登陆超时请重新登陆')
                }
              })
          }
        })
    },
    async searchExerciseByChildCategoryAlias (item) {
      this.showLoading = true
      this.acategoryAlias = item.alias
      this.acategoryId = item.id
      this.item = item
      const that = this
      const param = new URLSearchParams()
      // param.append('categoryId', that.item.id)
      if (that.item.alias) {
        param.append('categoryAlias', that.item.alias)
      }
      param.append('pageNo', this.pageNo)
      param.append('PageSize', this.PageSize)
      await this.$http8081
        .post(`/question-search/flipListByCategoryAlias`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s20006) {
            that.total = res.data.data.total
            that.showLoading = false
            that.tableData = res.data.data.records
            that.$message.success(res.data.statusMsg)
          }
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.searchExerciseByChildCategoryAlias(_that.item)
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  _that.$router.push({ name: 'login' })
                  _that.$message.success('登陆超时请重新登陆')
                }
              })
          }
        })
    },
    async removeExercise (scope) {
      this.scope1 = scope
      this.showLoading = true
      const that = this
      const param = new URLSearchParams()
      param.append('parentId', this.scope1.row.id)
      await this.$http8081
        .post(`/question-search/getChoiceOptionByParent`, param)
        .then(function (res) {
          const options = res.data.data
          const list = {}
          for (var key in options) {
            list[options[key].letter] = options[key]
          }
          that.option = list
        })
      const param2 = new URLSearchParams()
      if (this.option.A) {
        this.optionStr = this.option.A.id
      }
      if (this.option.B) {
        this.optionStr += ',' + this.option.B.id
      }
      if (this.option.C) {
        this.optionStr += ',' + this.option.C.id
      }
      if (this.option.D) {
        this.optionStr += ',' + this.option.D.id
      }
      if (this.option.E) {
        this.optionStr += ',' + this.option.E.id
      }
      if (this.option.F) {
        this.optionStr += ',' + this.option.F.id
      }
      param2.append('id', scope.row.id)
      param2.append('choiceOptionIdList', this.optionStr)
      this.$http8080
        .post(`/question-operate/remove`, param2)
        .then(function (res) {
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.removeExercise(_that.scope1)
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  _that.$router.push({ name: 'login' })
                  _that.$message.success('登陆超时请重新登陆')
                }
              })
          }
          if (res.data.statusCode === 20004) {
            that.$message.success(res.data.statusMsg)
            const param = new URLSearchParams()
            param.append('categoryId', that.acategoryId)
            param.append('categoryAlias', that.acategoryAlias)
            that.$http8081
              .post(`/question-search/flipListByCategoryAlias`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s20006) {
                  that.total = res.data.data.total
                  that.showLoading = false
                  that.tableData = res.data.data.records
                } else {
                  that.$message.error(res.data.statusMsg)
                }
              })
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
    },
    changeEditExeciseCateId (item) {
      this.editExerciseList.categoryId = item.id
      this.editExerciseList.categoryAlias = item.alias
    },
    async showEditChild (scope) {
      this.item.id = scope.row.category
      if (scope.row.kind === 1) {
        this.changeFlag = false
      } else {
        this.changeFlag = true
      }
      this.kinds = scope.row.kind.toString()
      this.rightOption = scope.row.rightOption
      this.editExerciseList.categoryId = scope.row.categoryId
      this.editExerciseList.categoryAlias = scope.row.categoryAlias
      const that = this
      const param = new URLSearchParams()
      param.append('keyName', this.keyName)
      // 查询子字典数据
      await this.$http8081
        .post(`/dictionary-search/flipListByKeyName`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.showEditChild(_that.keyName)
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  _that.$router.push({ name: 'login' })
                  _that.$message.success('登陆超时请重新登陆')
                }
              })
          }
          if (res.data.statusCode === $$.s20006) {
            that.ChildCategoryList = res.data.data
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
      this.editChild = true
      this.editExerciseList.id = scope.row.id
      this.editExerciseList.content = scope.row.content
      this.editExerciseList.kind = this.kind
      this.editExerciseList.rightOption = scope.row.rightOption
      this.editExerciseList.rightOptionContent = scope.row.rightOptionContent
      const param2 = new URLSearchParams()
      param2.append('parentId', scope.row.id)
      await this.$http8081
        .post(`/question-search/getChoiceOptionByParent`, param2)
        .then(function (res) {
          const options = res.data.data
          const list = {}
          for (var key in options) {
            list[options[key].letter] = options[key]
          }
          that.option = list
          that.listArr = JSON.stringify(list)
        })
    },
    toJSONarr () {
      for (var i in this.optionObj) {
        this.optionArr.push(this.optionObj[i])
      }
      this.optionArr = JSON.stringify(this.optionArr)
    },
    async editExercise () {
      this.optionArr = []
      const that = this
      const param = new URLSearchParams()
      param.append('id', this.editExerciseList.id)
      param.append('content', this.editExerciseList.content)
      param.append('kind', this.kinds)
      param.append('categoryId', this.editExerciseList.categoryId)
      param.append('categoryAlias', this.editExerciseList.categoryAlias)
      param.append('rightOption', this.editExerciseList.rightOption)
      param.append(
        'rightOptionContent',
        this.editExerciseList.rightOptionContent
      )
      this.showLoading = true
      if (this.changeFlag) {
        if (this.option.A) {
          this.optionObj.A.content = this.option.A.content
          this.optionObj.A.id = this.option.A.id
        }
        if (this.option.B) {
          this.optionObj.B.content = this.option.B.content
          this.optionObj.B.id = this.option.B.id
        }
        if (this.option.C) {
          this.optionObj.C.content = this.option.C.content
          this.optionObj.C.id = this.option.C.id
        }
        if (this.option.D) {
          this.optionObj.D.content = this.option.D.content
          this.optionObj.D.id = this.option.D.id
        }
        if (this.option.E) {
          this.optionObj.E.content = this.option.E.content
          this.optionObj.E.id = this.option.E.id
        }
        if (this.option.F) {
          this.optionObj.F.content = this.option.F.content
          this.optionObj.F.id = this.option.F.id
        }
        this.toJSONarr()
      } else {
        if (this.option.A) {
          this.optionObj.A.content = this.option.A.content
          this.optionObj.A.id = this.option.A.id
        }
        if (this.option.B) {
          this.optionObj.B.content = this.option.B.content
          this.optionObj.B.id = this.option.B.id
        }
        delete this.optionObj.C
        delete this.optionObj.D
        delete this.optionObj.E
        delete this.optionObj.F
        this.toJSONarr()
      }
      param.append('choiceOptionList', this.optionArr)
      await this.$http8080
        .post(`/question-operate/modify`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s20002) {
            that.searchChildDictionaryByKeyName(that.keyName)
            that.$message.success(res.data.statusMsg)
            that.editChild = false
            that.optionArr = []
            const param = new URLSearchParams()
            param.append('categoryId', that.acategoryId)
            param.append('categoryAlias', that.acategoryAlias)
            that.$http8081
              .post(`/question-search/flipListByCategoryAlias`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s20006) {
                  that.tableData = res.data.data.records
                  that.showLoading = false
                } else {
                  that.$message.error(res.data.statusMsg)
                }
              })
          } else {
            that.$message.error('修改失败')
          }
        })
    }
  }
}
</script>
<style>
#exercise-form {
  margin-top: 10px;
}
.exerciseList {
  margin-top: 20px;
}
.page {
  width: 570px;
  margin: 0 auto;
}
.errMessage {
  color: rgb(144, 147, 153);
  font-size: 12px;
  font-weight: 700;
  text-align: center;
}
.tipStyle2 {
  position: absolute;
  left: 250px;
  top: 40px;
  font-size: 12px;
  color: #666;
}
.loading2 {
  width: 100%;
  margin-top: 20px;
  text-align: center;
  position: relative;
  top: 50%;
  left: 50%;
}
.el-icon-loading2 {
  font-size: 50px;
}
.el-dialog {
  width: 65%;
  height: auto;
}
.editInput {
  width: 400px;
}
.el-form-item__label {
  width: 300px;
}
.pagenation {
  position: absolute;
  right: 20px;
  top: 30px;
}
.excriseOption {
  width: 30%;
  /* margin-top: 10px; */
}
.el-dialog__footer {
  position: absolute;
  right: 14px;
  bottom: 24px;
}
.excriseContent .el-textarea__inner {
  min-height: 150px !important;
}
</style>
